clc;
clearvars;
%% Load or Make Data
TempDataFile='Data\FusionEstimationData1.mat';
ReplaceChaseFlag=true;
if exist(TempDataFile,'file')
    Yes_NO = questdlg({'Cash File Exist','Replace it?'});
    if strcmp(Yes_NO,'No') || strcmp(Yes_NO,'Cancel')
        ReplaceChaseFlag=false;
    end
end
if ReplaceChaseFlag
RNGState=rng('default');
K=68;

FoldNumber=10;
[Train,Test]=GetKFoldRegressorDataFromRepository(FoldNumber,true);
EstimatedWs=zeros(FoldNumber*Test.SNum,3);
AgentWs=zeros(FoldNumber*Test.SNum,1);
FeaturesIndexs=[1:5,8:11,28:29,30:39]; %All Features Included [1:5,8:11,28,29,30:39]
for f=1:FoldNumber
    fprintf('Analyze fold %02d of %d.\n',f,FoldNumber)
    KNNRegressor = KNNReg(Train.Features(:,FeaturesIndexs,f),Train.Label(:,f),'NumNeighbors',K,'RegresiorMethod','InverseDistance');
    PredictedValue=GetRegValue(KNNRegressor,Test.Features(:,FeaturesIndexs,f));
    EstimatedWs(((f-1)*Test.SNum)+1:f*Test.SNum,:)=[PredictedValue,Test.BestFittedW(:,:,f)];
    AgentWs(((f-1)*Test.SNum)+1:f*Test.SNum,:)=Test.Label(:,f);
end


%%
EstimatedWs(:,2)=[];
Winexes=1+(dec2bin(1:14,4)=='1');
BestF2D=inf;
BestTreshold2D=[];
BestI2D=0;
options = optimoptions('ga','FunctionTolerance',1e-10,'PopulationSize',200,'Display','final');
for i=1:14
    Fun=@(thl)mean(abs(AgentWs-FusionW2D(EstimatedWs,thl,Winexes(i,:))));
    [Treshold,F]=ga(Fun,2,[],[],[],[],zeros(1,2)-0.01,ones(1,2)+0.01,[],options);
    if F<BestF2D
        BestF2D=F;
        BestTreshold2D=Treshold;
        BestI2D=i;
    end
end
WIndex2D=Winexes(BestI2D,:);
WFusion2D=FusionW2D(EstimatedWs,BestTreshold2D,WIndex2D);


%%
Winexes=1+(dec2bin(1:2,2)=='1');
BestF1D=inf;
BestTreshold1D=[];
BestI1D=0;
options = optimoptions('ga','FunctionTolerance',1e-10,'PopulationSize',200,'Display','final');
for i=1:2
    Fun=@(thl)mean(abs(AgentWs-FusionW1D(EstimatedWs,thl,Winexes(i,:))));
    [Treshold,F]=ga(Fun,1,[],[],[],[],-0.01,1.01,[],options);
    if F<BestF1D
        BestF1D=F;
        BestTreshold1D=Treshold;
        BestI1D=i;
    end
end
WIndex=Winexes(BestI1D,:);
WFusion1D=FusionW1D(EstimatedWs,BestTreshold1D,WIndex);
save(TempDataFile)
else
load(TempDataFile)
end
MAEFusion2D=mean(abs(AgentWs-WFusion2D))
MAEFusion1D=mean(abs(AgentWs-WFusion1D))
MAEKnn=mean(abs(AgentWs-EstimatedWs(:,1)))
MAEMAP=mean(abs(AgentWs-EstimatedWs(:,2)))
%%
